#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <string.h>
#include<arpa/inet.h>
#include <error.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <pthread.h>
void* recvsocket(void* arg)//接受来着客户端数据的线程
{
    pthread_t thread_id = pthread_self();
    printf("--server sendsocket thread id: %lu\n", thread_id);
    int st = *(int*)arg;
    char s[1024];
    while (1)
    {
        memset(s, 0, sizeof(s));
        int rc = recv(st, s, sizeof(s), 0);
        if (rc <= 0)//代表socket被关闭（0）或者出错（-1）
        {
            printf("sercver recv fail:%d\n", rc);
            break;
        }
        printf("server receive:%s\n", s);
    }
    return NULL;
}
void* sendsocket(void* arg)//向客户端socket发送数据的线程
{
    pthread_t thread_id = pthread_self();
    printf("--server sendsocket thread id: %lu\n", thread_id);
    int st = *(int*)arg;
    char s[1024];
    while (1)
    {
        memset(s, 0, sizeof(s));
        scanf("%s", s);
        int sc = send(st, s, strlen(s), 0);
        printf("server send finished!\n");
    }
}
//执行命令 ./server.out 8080
int main(int arg, char* args[])
{
    if (arg < 2)
    {
        printf("arg<2\n");
        return -1;
    }
    int port = atoi(args[1]);
    int st = socket(AF_INET, SOCK_STREAM, 0);

    //setsockopt 设置socket的一个属性，让地址可以重用。
    int on = 0;
    if (setsockopt(st, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1)
    {
        printf("setsockopt failed:%s\n", strerror(errno));
        return EXIT_FAILURE;
    }
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    //INADDR_ANY表示这个服务器上的所有Ip地址。一台服务器可以有多个ip地址。将socket绑定到这个机器的所有ip地址上
    addr.sin_addr.s_addr = htonl(INADDR_ANY);

    //将ip地址与server程序绑定
    if (bind(st, (struct sockaddr*) & addr, sizeof(addr)) == -1)
    {
        printf("bind fail %s\n", strerror(errno));
        return EXIT_FAILURE;
    }
    //server开始监听。 20代表同时有多少个连接过来（20并发）
    if (listen(st, 20) == -1)
    {
        printf("listen fail %s\n", strerror(errno));
        return EXIT_FAILURE;
    }
    //char s[1024];
    int client_st = 0;//客户端socket
    struct sockaddr_in client_addr;//客户端IP

    pthread_t thrd1, thrd2;//定义一个线程
    while (1)
    {
        memset(&client_addr, 0, sizeof(client_addr));
        socklen_t len = sizeof(client_addr);
        //accept会阻塞，直到有客户端连接过来。accept返回客户端的描述符
        client_st = accept(st, (struct sockaddr*) & client_addr, &len);
        if (client_st == -1)
        {
            printf("accept fail %s\n", strerror(errno));
            return EXIT_FAILURE;
        }
        //打印客户端的ip地址
        printf("accept ip : %s:%d\n", inet_ntoa(client_addr.sin_addr), htons(client_addr.sin_port));
        pthread_create(&thrd1, NULL, recvsocket, &client_st);
        pthread_create(&thrd2, NULL, sendsocket, &client_st);
    }
    close(st);
    getchar();
}